package com.qk.management.aop;

import cn.hutool.json.JSONUtil;
import com.qk.common.Result;
import com.qk.common.constant.LogStatusConstants;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.entity.OperateLog;
import com.qk.management.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Author ZgYn
 * @Date 2025/10/17 17:22
 * @Name LogRecordAspect
 */
@Slf4j
@Aspect
@Component
public class LogRecordAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Pointcut("@annotation(com.qk.management.aop.anno.LogAnno)")
    public void pc(){

    }

    @Around("pc()")
    public Object around(ProceedingJoinPoint pjp) {
        Object result = null;
        try {
            long startTime = System.currentTimeMillis();
            result = pjp.proceed();
            long endTime = System.currentTimeMillis();
            long time = endTime - startTime;
            String className = pjp.getTarget().getClass().getName();
            String methodName = pjp.getSignature().getName();
            Object[] args = pjp.getArgs();
            String methodParams = JSONUtil.toJsonStr(args);
            log.info("LogRecordAspect around time: {}ms", time);
            OperateLog operateLog = OperateLog.builder()
                    .className(className)
                    .methodName(methodName)
                    .methodParams(methodParams)
                    .operateUserId(CurrentUserContextHolders.get())
                    .costTime(time)
                    .operateTime(LocalDateTime.now())
                    .returnValue(JSONUtil.toJsonStr(result))
                    .build();
            try {
                operateLogMapper.insert(operateLog);
            } catch (Exception e) {
                log.error("记录操作日志失败{}", e.getMessage());
            }
        } catch (Throwable throwable) {
            log.error("操作失败{}", throwable.getMessage());
            result = Result.error(LogStatusConstants.LOG_ERROR);
        }
        return result;
    }
}
